package cave.ui;

import java.util.ArrayList;
import cave.game.InputEvent;
import cave.renderer.RenderList;

public class RadioButtonGroup implements DynamicUiItem {

	private RadioButtonGroupListener listener;
	private ArrayList<RadioButton> buttons;
	private int selectedIndex;
	
	public RadioButtonGroup(RadioButtonGroupListener listener) {
		this.listener = listener;
		buttons = new ArrayList<RadioButton>();
		selectedIndex = -1;
	}
	
	public RadioButtonGroup(ArrayList<RadioButton> buttons, RadioButtonGroupListener listener) {
		this.listener = listener;
		this.buttons = buttons;
		selectedIndex = -1;
		for (int i = 0; i < buttons.size(); i++) {
			buttons.get(i).setRadioButtonGroup(this);
		}
	}

	@Override
	public void draw(RenderList renderList) {
		for (int i = 0; i < buttons.size(); i++) {
			buttons.get(i).draw(renderList);
		}
	}

	@Override
	public void destroy() {
		for (int i = 0; i < buttons.size(); i++) {
			buttons.get(i).destroy();
		}
	}

	@Override
	public void update(float dt, ArrayList<InputEvent> events) {
		for (int i = 0; i < buttons.size(); i++) {
			buttons.get(i).update(dt, events);
		}
	}
	
	public void setSelected(int newIndex) {
		if (newIndex != selectedIndex) {
			int oldIndex = selectedIndex;
			if (oldIndex != -1) {
				buttons.get(selectedIndex).setSelected(false);
			}
			buttons.get(newIndex).setSelected(true);
			selectedIndex = newIndex;
			listener.onSelectionChange(oldIndex, newIndex);
		}
	}
	
	public int getSelectedIndex() {
		return selectedIndex;
	}
	
	public RadioButton getSelectedButton() {
		return buttons.get(selectedIndex);
	}
	
	public void setSelectedButton(RadioButton button) {
		for (int i = 0; i < buttons.size(); i++) {
			if (button == buttons.get(i)) {
				setSelected(i);
			}
		}
	}
	
	public ArrayList<RadioButton> getButtons() {
		return buttons;
	}
	
	public void addRadioButton(RadioButton button) {
		button.setIndex(buttons.size());
		button.setRadioButtonGroup(this);
		buttons.add(button);
	}
	
	public void removeRadioButton(RadioButton button) {
		buttons.remove(button);
	}
}
